package com.atguigu.gmall.flume.log.interceptor;

import com.atguigu.gmall.flume.utils.JSONUtil;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;

import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;

public class ETLInterceptor implements Interceptor {
    @Override
    public void initialize() {

    }

    @Override
    public Event intercept(Event event) {
        // 1. 获取body并转换成字符串
        byte[] body = event.getBody();
        String log = new String(body, StandardCharsets.UTF_8);

        // 2. 过滤字符串是否是一个合法的json
        if (JSONUtil.isValidateJSON(log))
            return event;
        else
            return null;
    }

    @Override
    public List<Event> intercept(List<Event> list) {
        Iterator<Event> iterator = list.iterator();

        while (iterator.hasNext()) {
            Event next = iterator.next();
            if (intercept(next) == null)
                iterator.remove();
        }
        return list;
    }

    @Override
    public void close() {

    }

    public static class Build implements Builder{

        @Override
        public Interceptor build() {
            return new ETLInterceptor();
        }

        @Override
        public void configure(Context context) {

        }
    }
}
